<template>
	<view>
		<!-- 顶部背景图 -->
		<view class="topbgimg">
			<image src="https://iflytts.oss-cn-qingdao.aliyuncs.com/website/img/webxzy/twoxze_7.png" mode=""></image>
		</view>
		<custom-tabs type="c1" :value="value" tabSpacing="55" @change="changeIndex"
			:defaultTextStyle="{color:'#8D8D8D'}"
			:activeLineStyle="{'background-color':'#333333','width':'37rpx','height':'6rpx'}">
			<custom-tab-pane label="短视频链接" name="c1_1">
				<!-- <view class="progress" v-if="showProgress">
					<u-line-progress :percentage="percentage" activeColor='#4B85FF' />
				</view> -->
				<view class="short_video_link">
					<view class="addAudio" contenteditable="true">
						<textarea class="input" maxlength="-1" placeholder="粘贴复制短视频链接" v-model="link"></textarea>
						<view class="tools">
							<view class="tools_left">
								<view class="left" @click="clearText">
									<image src="../../static/new/clear.png" mode=""></image>
									<text class="text">清除文本</text>
								</view>
							</view>
						</view>
					</view>


					<view class="addAudio" v-if="shortRes">
						<textarea class="input" maxlength="-1" placeholder="文案提取结果" v-model="shortRes"></textarea>
					</view>
					<view class="button" v-if="!shortRes">
						<view class="button_center">
							<u-button text="提取文案" color="#4B85FF" size="large" @click="shortExtraction"></u-button>
						</view>
					</view>
					<view class="button" v-if="shortRes">
						<view class="button_left">
							<u-button text="重新提取" color="#4B85FF" size="large" @click="shortExtraction"></u-button>
						</view>
						<view class="button_right">
							<u-button text="复制文案" color="rgba(0,0,0,0)" size="large" @click="shortCopy"></u-button>
						</view>
					</view>
					<view class="footer_title">
						<text>温馨提示：文案提取只支持视频中的语音文案提取(视频时长不超过15分钟),不支持图文中文案提取。</text>
					</view>
					<!-- 视频播放的组件 获取视频时长 不展示 -->
					<video v-show="video" id="video" :controls="controls" :src="video_url" :poster="imgUrl"
						@loadedmetadata="videoUrl">
					</video>
				</view>
			</custom-tab-pane>
			<custom-tab-pane label="本地音视频" name="c1_2">
				<!-- <view class="progress" v-if="showProgress">
					<u-line-progress :percentage="percentage" activeColor='#4B85FF' />
				</view> -->
				<view class="local_video">
					<view class="addLocalAudio">
						<audios1 @importPlay="importPlay" @WaddAudio="WaddAudio" @NaddAudio="NaddAudio" :Audio="Audio">
						</audios1>
					</view>
					<view class="addAudio" v-if="localRes">
						<textarea class="input" maxlength="-1" placeholder="文案提取结果" v-model="localRes"></textarea>
					</view>
					<view class="button" v-if="!localRes">
						<view class="button_center">
							<u-button text="提取文案" color="#4B85FF" size="large" @click="localExtraction"></u-button>
						</view>
					</view>
					<view class="button" v-if="localRes">
						<view class="button_left">
							<u-button text="重新提取" color="#4B85FF" size="large" @click="localExtraction"></u-button>
						</view>
						<view class="button_right">
							<u-button text="复制文案" color="rgba(0,0,0,0)" size="large" @click="localCopy"></u-button>
						</view>
					</view>
				</view>
			</custom-tab-pane>
			<custom-tab-pane label="Txt" name="c1_3">
				<view class="txt">
					<view class="videoAdd" @click="uploadTxt" v-if="!txtPath">
						<view class="videoAdd_image">
							<image src="/static/tools/addaudio.png" mode=""></image>
						</view>
						<view class="text">上传TXT文件</view>
					</view>
					<view class="txt_box" v-else>
						<view class="AudioCentre">
							<view class="AudioCentre_top">{{ txtName }}</view>
							<view class="AudioCentre_bottom">{{ txtTime |  formatDate}}</view>
						</view>
						<view class="AudioFile_right" @click="uploadTxt">更换txt</view>
					</view>
					<view class="addAudio" v-if="txtRes">
						<textarea class="input" maxlength="-1" placeholder="文案提取结果" v-model="txtRes"></textarea>
					</view>
					<view class="button" v-if="!txtRes">
						<view class="button_center">
							<u-button text="提取文案" color="#4B85FF" size="large" @click="txtExtraction"></u-button>
						</view>
					</view>
					<view class="button" v-if="txtRes">
						<view class="button_left">
							<u-button text="重新提取" color="#4B85FF" size="large" @click="txtExtraction"></u-button>
						</view>
						<view class="button_right">
							<u-button text="复制文案" color="rgba(0,0,0,0)" size="large" @click="txtCopy"></u-button>
						</view>
					</view>
				</view>
			</custom-tab-pane>
		</custom-tabs>
		<!-- 非会员看广告提示 -->
		<u-modal :show="vipShow" :title="'温馨提示'" :content="'您还不是会员,此功能需开通会员才可使用。'" cancelText="取消" confirmText="去开通"
			showCancelButton="true" @cancel="cancel" @confirm="govip" :closeOnClickOverlay="true"
			@close="vipShow = false"></u-modal>

	</view>
</template>
<script>
	import {
		apiMixUrlApi
	} from '@/api/assemb.js';
	import {
		isLogin,
		vipType
	} from '@/business/login.js';
	import {
		uploadAudioFile
	} from '@/utils/upload/index.js';
	import {
		audioTypeJudgment
	} from '@/business/audioTypeJudgment.js';
	let app = getApp();
	const innerAudioContext = uni.createInnerAudioContext(); // 创建内部 audio
	const manager = uni.getFileSystemManager();
	export default {
		data() {
			return {
				video: false,
				video_url: '',
				timer: null,
				timers: null,
				percentage: 0,
				showProgress: false,
				vipShow: false,
				value: 1,
				link: '',
				shortRes: '',
				Audio: {
					audioUrl: '',
					audioName: '',
					audioTime: 0,
					isPlay: 0, //0暂停，1播放
					duration: 0 // 总时长
				},
				localRes: '',
				txtPath: '',
				txtName: '',
				txtTime: '',
				txtRes: '',
				videoTime: '',
				isImage: 0, //判断是否是图文
				imageTime: null,
				attemptCount: 0, //提取次数限制
				attemptFalse: false,
				isLoad: false //判断是否加载过视频
			}
		},
		onShow() {
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
			// this.isVip = true;
		},
		onUnload() {
			clearInterval(this.timer);
			clearInterval(this.timers);

		},

		//添加Js

		//时间戳的处理    
		filters: {
			formatDate: function(value) {
				var date = new Date();
				//date.setTime(value);
				var month = date.getMonth() + 1;
				var hours = date.getHours();
				if (hours < 10)
					hours = "0" + hours;
				var minutes = date.getMinutes();
				if (minutes < 10)
					minutes = "0" + minutes;
				var time = date.getFullYear() + "-" + month + "-" + date.getDate() +
					" " + hours + ":" + minutes;
				return time;
			}

		},
		methods: {
			//视频播放器加载触发 获取视频时长，视频链接获取到以后自动触发
			videoUrl(e) {
				if (!this.isLoad) {
					console.log('执行了一次')
					clearTimeout(this.imageTime)
					this.videoTime = e.target.duration
					console.log(e.target.duration)
					if (this.videoTime < 900) {
						console.log('这里')
						this.shengdao(this.video_url);
					} else {
						uni.showToast({
							title: '视频超过十五分钟,请重新选择',
							duration: 2000,
							icon: 'none'
						})
					}
					this.isLoad = true;
				}
			},
			async shengdao(url, index) {
				const _this = this
				console.log(url, '000000000');
				let c1 = new wx.cloud.Cloud({
					// 资源方 AppID
					resourceAppid: getApp().globalData.resourceAppid,
					// 资源方环境 ID
					resourceEnv: getApp().globalData.resourceEnv,
				});
				await c1.init();
				return new Promise((resolve, reject) => {
					c1.callFunction({
						name: "recordingRecognition",
						data: {
							EngineModelType: "16k_zh",
							ChannelNum: 1,
							SpeakerDiarization: 0,
							SpeakerNumber: 0,
							ResTextFormat: 0,
							SourceType: 0,
							Url: url
						},
					}).then((res) => {
						_this.timers = setInterval(() => {
							_this.renovate(res.result.Data.TaskId, index);
						}, 2000)
					});
				});
			},
			async renovate(taskId, index) {
				const _this = this
				console.log(taskId, '000000000');
				let c1 = new wx.cloud.Cloud({
					// 资源方 AppID
					resourceAppid: getApp().globalData.resourceAppid,
					// 资源方环境 ID
					resourceEnv: getApp().globalData.resourceEnv,
				});
				await c1.init();
				return new Promise((resolve, reject) => {
					c1.callFunction({
						name: "turnText",
						data: {
							TaskId: taskId,
						},
					}).then((res) => {
						if (res.result.Data.StatusStr == 'failed') {
							uni.showToast({
								title: '提取失败请重试',
								duration: 2000,
								icon: 'none',
								success() {
									clearInterval(_this.timers)
									_this.getText = false;
									_this.attemptFalse = false;
									return
								}
							});
						}
						if (res.result.Data.StatusStr == "success") {
							1
							clearInterval(_this.timers);
							if (index == 1) {
								_this.localRes = res.result.Data.Result.replace(/\[[^\]]*\]/g, "")
									.trim();
							} else {
								_this.shortRes = res.result.Data.Result.replace(/\[[^\]]*\]/g, "")
									.trim();
							}
							_this.showProgress = false;
							_this.attemptCount++; // 每次调用增加一次提取次数
							uni.setStorageSync('attemptCount', _this.attemptCount);
							// _this.percentage = 100;
							uni.showToast({
								title: '提取成功',
								duration: 2000,
								icon: 'success',
								success() {
									console.log('这个地方提取成功')
									clearInterval(_this.timers)
									_this.timers = null; //自己把timer置为null就好了
									_this.attemptFalse = true;
								}
							});
						}
					});
				});
			},


			txtCopy() {
				uni.setClipboardData({
					data: this.txtRes,
					showToast: true
				});
			},
			txtExtraction() {
				const _this = this
				_this.attemptCount = uni.getStorageSync('attemptCount')
				if (_this.attemptCount > 20) { // 检查是否超过20次尝试
					uni.showToast({
						title: '已达每日最大提取次数，请明天再试',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				_this.attemptCount++; // 每次调用增加一次提取次数
				uni.setStorageSync('attemptCount', _this.attemptCount);
				if (_this.txtPath == '') {
					uni.showToast({
						title: '请添加txt文件',
						duration: 2000,
						icon: 'none'
					});
				} else if (_this.isVip) {
					if (_this.txtPath.match(/\.[^.]+?$/)[0] == '.txt') {
						manager.readFile({
							filePath: _this.txtPath,
							encoding: 'utf-8',
							success: (res) => {
								console.log(res.data);
								_this.txtRes = res.data
							}
						})
					} else {
						uni.showToast({
							title: '请选择正确的txt文件',
							icon: 'none',
							duration: 2000
						})
					}

				} else {
					_this.vipShow = true
				}

			},
			uploadTxt() {
				let _this = this;
				wx.chooseMessageFile({
					count: 1, //默认100
					type: 'file',
					success: function(res) {
						console.log(res);
						_this.txtName = res.tempFiles[0].name
						_this.txtTime = res.tempFiles[0].time
						_this.txtPath = res.tempFiles[0].path
					}
				});

			},
			//本地视频提取
			localCopy() {
				uni.setClipboardData({
					data: this.localRes,
					showToast: true
				});
			},
			localExtraction() {
				const _this = this
				const previousLink = _this.previousLink || '';
				_this.attemptCount = uni.getStorageSync('attemptCount')
				if (_this.attemptCount > 20) { // 检查是否超过20次尝试
					uni.showToast({
						title: '已达每日最大提取次数，请明天再试',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				// _this.percentage = 0
				if (_this.Audio.audioUrl == '') {
					uni.showToast({
						title: '请添加音视频',
						duration: 2000,
						icon: 'none'
					});
				} else if (_this.isVip) {
					let prams = {
						url: _this.Audio.audioUrl
					};
					if (_this.Audio.audioUrl === previousLink && _this.attemptFalse == true) {
						console.log('111', _this.Audio.audioUrl);
						let res = _this.localRes
						_this.localRes = '',
							uni.showLoading({
								title: '提取中,请稍等',
								mask:true
							})
						setTimeout(() => {
							uni.showToast({
								title: '提取成功',
								duration: 2000,
								icon: 'success',
							});
							uni.hideLoading();
							_this.localRes = res
						}, 5000);
						_this.attemptCount++; // 每次调用增加一次提取次数
						uni.setStorageSync('attemptCount', _this.attemptCount);
						return;
					}
					uni.showLoading({
						title: '提取中,请稍等',
						mask:true
					})
					_this.previousLink = _this.Audio.audioUrl; // 更新当前链接为上次链接
					_this.shengdao(_this.Audio.audioUrl, 1);

				} else {
					_this.vipShow = true;
				}
			},
			//短视频链接提取
			shortCopy() {
				uni.setClipboardData({
					data: this.shortRes,
					showToast: true
				});
			},
			//提取视频链接
			shortExtraction() {
				this.isLoad = false;
				const _this = this
				// _this.percentage = 0
				_this.attemptCount = uni.getStorageSync('attemptCount')
				if (_this.attemptCount > 20) { // 检查是否超过20次尝试
					uni.showToast({
						title: '已达每日最大提取次数，请明天再试',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				if (_this.link.trim() == '') {
					uni.showToast({
						title: '请输入链接',
						duration: 2000,
						icon: 'none'
					});
				} else if (_this.isVip) {
					const previousLink = _this.previousLink || '';
					if (_this.link === previousLink && _this.attemptFalse == true) {
						let res = this.shortRes
						this.shortRes = '',
							uni.showLoading({
								title: '提取中,请稍等',
								mask:true
							})
						setTimeout(() => {
							uni.showToast({
								title: '提取成功',
								duration: 2000,
								icon: 'success',
							});
							uni.hideLoading();
							this.shortRes = res
						}, 5000);
						_this.attemptCount++; // 每次调用增加一次提取次数
						uni.setStorageSync('attemptCount', _this.attemptCount);
						return;
					}
					_this.previousLink = _this.link; // 更新当前链接为上次链接
					let prams = {
						url: _this.link
					};
					uni.showLoading({
						title: '加载中...',
						mask:true
					})
					apiMixUrlApi(prams, '1078', 'VideoParse').then(result => {
						if (result.code == 200) {
							_this.showProgress = true
							// _this.percentage = uni.$u.range(0, 100, _this.percentage + 30)
							console.log(result.data.url)
							//拿到视频地址触发视频组件
							_this.video_url = result.data.url

							uni.showLoading({
								title: '提取中,请稍等',
								mask:true
							})
							_this.imageTime = setTimeout(function() {
								console.log(_this.isImage)
								if (_this.isImage == 0) {
									_this.attemptFalse = false
									uni.hideLoading()
									uni.showModal({
										content: '提取失败,请更换链接'
									})
								}
							}, 9000);
						} else {
							uni.showToast({
								title: result.descinfo,
								icon: 'none',
								duration: 1500
							});
						}
					})

				} else {
					_this.vipShow = true;
				}
			},
			extractingText(url, type) {
				const _this = this
				let prams = {
					fileLink: url
				}
				apiMixUrlApi(prams, '1087', 'SubmitFileTrans').then(json => {
					// _this.percentage = uni.$u.range(0, 100, _this.percentage + 30)
					uni.showLoading({
						title: '提取中,请稍等',
						mask:true
					})
					if (type == 0) {
						_this.geoip(json.taskId)
					} else if (type == 1) {
						_this.geoipLocal(json.taskId)
					}
				})
			},
			/* local结果查询 */
			geoipLocal(taskId) {
				const _this = this
				let prams = {
					taskId
				}
				apiMixUrlApi(prams, '1088', 'GetAcsResponse').then(json => {
					if (json.descinfo == 'RUNNING') {
						clearInterval(_this.timers)
						_this.timers = setInterval(function() {
							_this.geoipLocal(prams.taskId)
						}, 5000)
						// _this.percentage = 90
					}
					if (json.descinfo == 'SUCCESS') {
						clearInterval(_this.timers)
						_this.localRes = json.text.replace(/\[[^\]]*\]/g, "").trim()
						_this.showProgress = false
						// _this.percentage = 100
						uni.hideLoading()
					}
				})
			},
			/* link结果查询 */
			geoip(taskId) {
				const _this = this
				let prams = {
					taskId
				}
				apiMixUrlApi(prams, '1088', 'GetAcsResponse').then(json => {
					if (json.descinfo == 'RUNNING') {
						clearInterval(_this.timer)
						_this.timer = setInterval(function() {
							_this.geoip(prams.taskId)
						}, 5000)
						// _this.percentage = 90
					}
					if (json.descinfo == 'SUCCESS') {
						clearInterval(_this.timer)
						_this.shortRes = json.text.replace(/\[[^\]]*\]/g, "").trim()
						_this.showProgress = false
						// _this.percentage = 100
						uni.hideLoading()
					}
				})
			},
			clearText() {
				this.link = ''
			},
			govip() {
				this.vipShow = false;
				if (uni.getStorageSync('OS') !== 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					uni.switchTab({
						url: '/pages/my/my'
					});
				}
			},
			cancel() {
				this.vipShow = false
			},
			changeIndex(e) {
				console.log('选中:', e)
			},
			WaddAudio() {
				let _this = this;
				uploadAudioFile().then(res => {
					_this.localRes = ''
					let Audio = {
						audioName: res.audioName,
						audioUrl: res.audioUrl,
						audioTime: res.audioTime,
						isPlay: 0, //0暂停，1播放
						importWay: 1
					};
					_this.Audio = Audio;
					audioTypeJudgment(res.audioUrl).then(ser => {
						_this.audioIndex = 1;
						if (!!ser) {
							_this.uploadAudioLink = ser;
							_this.audioPlaybackLink = _this.uploadAudioLink;
							_this.play();
						} else {
							_this.uploadAudioLink = res.audioUrl;
							_this.audioPlaybackLink = _this.uploadAudioLink;
							_this.play();
						}
					});
				});
			},
			/*
			 *	@	初始音乐播放
			 */
			importPlay(e) {
				this.audioIndex = e;
				this.audioPlaybackLink = this.uploadAudioLink;
				this.play();
			},
			/**
			 * 音频 播放
			 */
			play() {
				if (this.Audio.isPlay != this.audioIndex) {
					this.Audio.isPlay = this.audioIndex;
					innerAudioContext.src = this.audioPlaybackLink;
					innerAudioContext.play();
				} else if (this.Audio.isPlay == this.audioIndex) {
					innerAudioContext.pause();
					this.Audio.isPlay = 0;
				}
			},
		}
	}
</script>
<style lang="scss">
	/deep/.u-button {
		border-radius: 50rpx !important;
	}

	.topbgimg {
		position: absolute;
		width: 100%;
		height: 230rpx;
		top: 0;
		left: 0;
		z-index: -1;

		image {
			width: 100%;
			height: 100%;
		}
	}

	/deep/.tab .tab-bar-item.active {
		color: #333333 !important;
		font-weight: bold;
	}

	/deep/.tab .tab-bar {
		background-color: rgba(0, 0, 0, 0) !important;
	}

	/deep/.tab-bar::after {
		height: 0rpx !important;
	}

	.footer_title {
		width: 699rpx;
		margin-left: 35rpx;
		margin-top: 30rpx;
		font-size: 25rpx;
	}

	.txt {
		.txt_box {
			margin: auto;
			width: 676rpx;
			height: 211rpx;
			background: #ffffff;
			border: 1rpx solid #4B85FF;
			border-radius: 18rpx;
			display: flex;
			align-items: center;
			justify-content: space-evenly;

			.AudioCentre {
				width: 325rpx;

				.AudioCentre_top {
					width: 260rpx;
					height: 54rpx;
					line-height: 54rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-size: 33rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
				}

				.AudioCentre_bottom {
					width: 260rpx;
					height: 54rpx;
					line-height: 54rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-size: 22rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #a8a8a8;
				}
			}

			.AudioFile_right {
				width: 157rpx;
				height: 54rpx;
				background: #ffffff;
				border: 2rpx solid #4B85FF;
				border-radius: 27rpx;
				font-size: 24rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #4B85FF;
				text-align: center;
				line-height: 54rpx;
			}
		}

		.videoAdd {
			width: 679rpx;
			height: 200rpx;
			background: #ffffff;
			border: 1rpx dashed #4B85FF;
			border-radius: 18rpx;
			margin: auto;

			.videoAdd_image {
				width: 58rpx;
				height: 58rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #4B85FF;
				margin: auto;
				margin-top: 50rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.text {
				font-size: 29rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #4B85FF;
				width: 100%;
				text-align: center;
				margin-top: 20rpx;
			}
		}
	}

	.local_video {
		margin-top: 20rpx;

		.addLocalAudio {
			display: flex;
			justify-content: center;
		}
	}

	.progress {
		padding: 0 40rpx;
	}

	.button {
		margin-top: 62rpx;
		width: 100%;
		display: flex;
		justify-content: center;

		.button_left {
			width: 325rpx;
			margin-right: 30rpx;
		}

		.button_right {
			position: relative;
			width: 325rpx;
			border: 1px solid #4B85FF;
			border-radius: 50rpx;

			button {
				color: #4B85FF !important;
			}

			.right_other {
				display: flex;
				align-items: center;
				position: absolute;
				top: -21rpx;
				right: 0;
				width: 154rpx;
				height: 42rpx;
				background: #FF6600;
				border-radius: 21rpx 0rpx 0rpx 21rpx;

				text {
					line-height: 42rpx;
					margin-left: 18rpx;
					font-size: 18rpx;
					font-family: PingFang SC;
					color: #FFFFFF;
				}
			}
		}

		.button_center {
			width: 90%;
			margin: auto;
		}
	}

	.addAudio {
		margin: 0 auto;
		margin-top: 30rpx;
		position: relative;
		overflow: hidden;
		width: 707rpx;
		height: 378rpx;
		background: #FFFFFF;
		box-shadow: 1rpx 10rpx 33rpx 0rpx rgba(238, 238, 238, 0.76);
		border-radius: 12rpx;
		padding-bottom: 40rpx;

		.input {
			width: 620rpx;
			margin: 0 auto;
			color: #999999;
			overflow: visible;
			word-break: break-all;
			padding: 20rpx 35rpx;
			vertical-align: top;
			outline: none;
		}

		.clearButton {
			width: 120rpx;
			line-height: 55rpx;
			font-size: 28rpx;
			color: #ffffff;
			background: #999992;
			text-align: center;
			position: absolute;
			bottom: 20rpx;
			right: 20rpx;
			z-index: 33;
		}
	}

	.tools {
		height: 80rpx;
		padding-left: 30rpx;
		background-color: #ffffff;
		display: flex;
		justify-content: space-between;
		position: absolute;
		width: 100%;
		bottom: 0rpx;
		z-index: 9;

		.tools_left {
			display: flex;
			justify-content: space-between;

			.left {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #999999;
				font-size: 24rpx;

				image {
					width: 42rpx;
					height: 42rpx;
					margin-right: 6rpx;
				}
			}
		}
	}
</style>

<style>
	page {
		background-color: #F7FBFF;
	}
</style>